没明白这个参数修改是怎么搞的?

来源:2-8 Python定义实例方法

叁杯

2020-09-08 17:33

class Animal(object):
    def __init__(self, name, age, localtion):
        self.__name=name
        self.__age=age
        self.__localtion=localtion
    def get_name(self):
        return self.__name
    def get_age(self):
        return self.__age
    def get_location(self):
        return self.__location
    def set_info(self):
        self.__name=name
        self.__age=age
        self.__localtion=localtion
monkey=Animal('wukong',25,'China')
print(monkey.get_name())
monkey.set_info()
monkey.__name='Monkeyking'
print(monkey.get_name())

  File "C:/Users/Administrator.USER-20190923TT/PycharmProjects/untitled/learn", line 60, in <module>

    monkey.set_info()

  File "C:/Users/Administrator.USER-20190923TT/PycharmProjects/untitled/learn", line 55, in set_info

    self.__name=name

NameError: name 'name' is not defined


写回答 关注

2回答

  • hermaniu
    2021-11-19 10:47:29

    #!/usr/bin/python

    #-*- coding:utf-8 -*-

    class Animal(object):

        def __init__(self, name, age, localtion):

            self.__name=name

            self.__age=age

            self.__localtion=localtion

        def set_info(self,name,age,localtion):

            self.__name=name

            self.__age=age

            self.__localtion=localtion

        def get_return(self):

            return self.__name,self.__age,self.__localtion

    monkey=Animal('wukong',25,'China')

    print('initial monkey:',monkey.get_return())

    monkey.set_info('herman',22,'Japan')

    print('final monkey:',monkey.get_return())



  • 叁杯
    2020-09-08 17:36:53
    class Animal(object):
        def __init__(self, name, age, localtion):
            self.__name=name
            self.__age=age
            self.__localtion=localtion
        def get_name(self):
            return self.__name
        def get_age(self):
            return self.__age
        def get_location(self):
            return self.__location
        def set_info(self,name,age,localtion):
            self.__name=name
            self.__age=age
            self.__localtion=localtion
    monkey=Animal('wukong',25,'China')
    print(monkey.get_name())
    monkey.set_info(name='Monkey King',age=25,localtion='China')
    
    print(monkey.get_name())

    忘记定义参数了。哈哈  可以了

Python3 进阶教程(新版)

学习函数式、模块和面向对象编程,掌握Python高级程序设计

41910 学习 · 236 问题

查看课程

相似问题