Python:类(class)的变量声明

类(class)的变量声明

  1. 类变量
class Pyclass:
    name = 'Pyclass' # 类变量
    add = 'Pyclass is a ' # 类变量
    def say(self, content):
        print(content)
        
print(Pyclass.name)
print(Pyclass.add)

Pyclass.name = 'Pyclass_' # 修改类变量
print(Pyclass.name)
Pyclass
Pyclass is a 
Pyclass_
  1. 实例变量 & 局部变量
class Pyclass2:
    def __init__(self):
        self.name = 'Pyclass2' # 实例变量,创建对象时会自动调用
        self.add = 'Pyclass2 is a ' # 实例变量,创建对象时会自动调用

    def say(self):
        self.arg1 = 13 # 实例变量,只有类对象调用say()方法时,才有arg1变量

    def countprice(self, money):
        sale = 0.8 * money # 类内的局部变量,只在函数内有效
        print('Price: ', sale)

Testclass = Pyclass2()
print(Testclass.name)
print(Testclass.add)

Testclass.say()
print(Testclass.arg1)

Testclass.countprice(100)

Testclass.arg2 = 30 # 添加变量
print(Testclass.arg2)
Pyclass2
Pyclass2 is a 
13
Price:  80.0
30
  1. 利用 self.__dict__.update()
class Pyclass3:
    _defaults = {
        'arg1': 'path/test.txt',
        'arg2': 'good',
        'arg3': 5,
        'arg4': 0.8
    }
    def __init__(self):
        self.__dict__.update(self._defaults)
        print(self.arg3)

Testclass2 = Pyclass3()
5

感谢:

http://c.biancheng.net/view/2283.html
https://blog.csdn.net/huanjin_w/article/details/110390103

你可能感兴趣的:(基础操作,python)