Python类和对象属性

Python类和对象属性

Python类和对象属性

  什么是类和对象属性?有什么不同?为什么?在进入类和对象属性的比较和示例之前,让我们首先定义它们。类属性是属于某个类而不是特定对象的变量。此类的每个实例共享相同的变量。这些属性通常在init构造函数之外定义。

Python类和对象属性
Python类和对象属性

  实例/对象属性是属于一个(且仅一个)对象的变量。类的每个实例都指向它自己的属性变量。这些属性在init构造函数中定义。

  推荐:Python面向对象的基本概念

什么是dict方法?

  根据python文档对象。dict是用于存储对象(可写)属性的字典或其他映射对象。或者用简单的话来说,python中的每个对象都有一个由dict表示的属性。

什么是dict方法
Python类和对象属性

  该对象包含为该对象定义的所有属性。dict也称为映射代理对象。对用户定义的对象和类使用dict方法。

class DogClass:
    def __init__(self,name,color):
        self.name = name
        self.color = color
    
    def bark(self):
        if self.color == "black":
            return True
        else:
            return False
dc = DogClass('rudra','white')
print(dc.__dict__)


DogClass.__dict__

"""
Output: mappingproxy({'__module__': '__main__',
              '__init__': <function __main__.DogClass.__init__(self, name, color)>,
              'bark': <function __main__.DogClass.bark(self)>,
              '__dict__': <attribute '__dict__' of 'DogClass' objects>,
              '__weakref__': <attribute '__weakref__' of 'DogClass' objects>,
              '__doc__': None})
"""

为什么需要使用类属性和对象属性?

  在一个只有狗的平行世界中,每只狗都有一个名字和一个年龄。狗的总数必须始终保持最新。所有这些都必须在一个类中定义!这可能看起来像这样:

class Dog:
    dogs_count = 0
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print("Welcome to this world {}!".format(self.name))
        Dog.dogs_count += 1
    def __del__(self):
        print("Goodbye {} :(".format(self.name))
        Dog.dogs_count -= 1

  在这个类中,我们有一个类属性dogs_count。这个变量跟踪我们在狗狗世界中拥有的狗的数量。我们有两个实例属性,name和age。这些变量对每只狗都是唯一的(每个实例的属性都有不同的内存位置)。每次init执行函数时,都会dogs_count增加。同样——每次狗死去(不幸的是,狗不会永远活在这个世界上),调用这个del方法,dogs_count就会减少。

a = Dog("Max", 1)
print("Number of dogs: {}".format(Dog.dogs_count))
b = Dog("Charlie", 7)
del a
c = Dog("Spot", 4.5)
print("Number of dogs: {}".format(Dog.dogs_count))
del b
del c
print("Number of dogs: {}".format(Dog.dogs_count))
Output:
Welcome to this world Max!
Number of dogs: 1
Welcome to this world Charlie!
Goodbye Max :(
Welcome to this world Spot!
Number of dogs: 2
Goodbye Charlie :(
Goodbye Spot :(
Number of dogs: 0

  我们设法分配了一个对象独有的变量,同时拥有一个所有对象都包含的共享变量。

  推荐:使用Python截取屏幕截图的3种方法

属性的继承

Python类和对象属性
Python类和对象属性

  在打开这个话题之前,我们先来看看内置dict属性。类示例:

class Example:
    classAttr = 0
    def __init__(self, instanceAttr):
        self.instanceAttr = instanceAttr
a = Example(1)
print(a.__dict__)
print(Example.__dict__)
Output:
{'instanceAttr': 1}
{'__module__': '__main__', '__doc__': None, '__dict__': <attribute '__dict__' of 'Example' objects>, '__init__': <function Example.__init__ at 0x7f8af2113f28>, 'classAttr': 0, '__weakref__': <attribute '__weakref__' of 'Example' objects>}

  类和对象都有一个带有属性键和值的字典。类字典存储了实例不包含的多个内置属性。

b = Example(2)
print(b.classAttr)
print(Example.classAttr)
b.classAttr = 653
print(b.classAttr)
print(Example.classAttr)
Output:
0
0
653
0

  类的每个实例都共享相同的类属性。我们改变了某个实例的类属性,但共享变量实际上并没有改变。查看这些元素的字典将提供进一步的见解:

b = Example(2)
print(b.__dict__)
print(Example.__dict__)
b.classAttr = 653
print(b.__dict__)
print(Example.__dict__)
Output:
{'instanceAttr': 2}
'__module__': '__main__', '__doc__': None, '__dict__': <attribute '__dict__' of 'Example' objects>, '__init__': <function Example.__init__ at 0x7f8af2113f28>, 'classAttr': 0, '__weakref__': <attribute '__weakref__' of 'Example' objects>}
{'instanceAttr': 2, 'classAttr': 653}
{'__module__': '__main__', '__doc__': None, '__dict__': <attribute '__dict__' of 'Example' objects>, '__init__': <function Example.__init__ at 0x7f8af2113f28>, 'classAttr': 0, '__weakref__': <attribute '__weakref__' of 'Example' objects>}

  我们注意到classAttr已添加到对象的字典中,并带有修改后的值。类的字典保持不变,这表明类属性有时可以表现为实例属性。

  推荐:如何将Python添加到Path环境变量

总结

  以上是晓得博客为你介绍的Python类和对象属性的内容,总而言之,类和对象属性非常有用,但一起使用时会变得混乱。当每个对象需要共享一个变量(例如计数器)时,类属性是有利的。当每个唯一对象都需要自己的值时,对象属性具有优势,这使它们与其他对象不同。

  推荐:零基础如何开始学习Python

给文章评分

晓得博客,版权所有丨如未注明,均为原创
晓得博客 » Python类和对象属性

转载请保留链接:https://www.pythonthree.com/class-and-object-attributes/

Claude、Netflix、Midjourney、ChatGPT Plus、PS、Disney、Youtube、Office 365、多邻国Plus账号购买,ChatGPT API购买,优惠码XDBK,用户购买的时候输入优惠码可以打95折

Chatgpt-Plus注册购买共享账号
滚动至顶部