python 类变量和实例变量

 

类变量是在类空间中命名的,就是不加self的变量。

因此,程序不能直接访问这些变量,必须通过类名+类变量来访问, 不管是在全局范围内还是函数内访问这些类变量,都必须使用类名进行访问

class Address:
    detail = "guangzhou"
    post_code = "510660"
    def info(self):
        #尝试直接访问类变量
        #print(detail) #报错

        #通过类类访问类变量
        print(Address.detail)
        print(Address.post_code)

#通过类来访问Address 类的类变量
print(Address.detail)
addr = Address()
addr.info()
#修改Address类的类变量
Address.detail = "fushan"

Address.post_code = "460110"
addr.info()
guangzhou
guangzhou
510660
fushan
460110
请按任意键继续. . .

实际上, python完全允许使用实例(对象)来访问对象所属类的类变量(当然还是推荐使用类访问类变量)

class Record:

    #define two class variable
    item = "鼠标"
    date = "2016"
    def info(self):
        print("In info method : ", self.item)
        print("In info method: ",self.date)

rc = Record()
#也可以通过实例来访问类变量
print(rc.item)
print(rc.date)
rc.info()
鼠标
2016
In info method :  鼠标
In info method:  2016
请按任意键继续. . .

实际上,程序通过对象访问类变量,其本质还是通过类名在访问类变量

由于通过对象访问类变量的本质还是类名在访问,因此如果类变量发生了改变,当程序访问这些类变量时也会读到修改之后的值

class Record:

    #define two class variable
    item = "鼠标"
    date = "2016"
    def info(self):
        print("In info method : ", self.item)
        print("In info method: ",self.date)

rc = Record()
#也可以通过实例来访问类变量
print(rc.item)
print(rc.date)
#由于通过对象访问类变量的本质还是类名在访问,因此如果类变量发生了改变,当程序访问这些类变量时也会读到修改之后的值
Record.item = "键盘"
Record.date = "2021"
rc.info()
鼠标
2016
In info method :  键盘
In info method:  2021
请按任意键继续. . .

 

 

class Record:

    #define two class variable
    item = "鼠标"
    date = "2016"
    def info(self,item,date):
        self.item = item
        self.date = date
rc = Record()
print(rc.item)
print(rc.date)
rc.info("display","2021")#修改的还是实例(self)的变量item,date,
print(rc.item)
print(rc.date)
print("-"*30)
print(Record.item)#item,date不会被改变
print(Record.date)        
鼠标
2016
display
2021
------------------------------
鼠标
2016
请按任意键继续. . .

 

posted @ 2021-12-12 12:01  朵朵奇fa  阅读(360)  评论(0编辑  收藏  举报