Stay Hungry,Stay Foolish!

Python Class Attributes

Class attributes

https://www.geeksforgeeks.org/class-instance-attributes-python/

类属性,属于类自己,但是被所有的实例共享。

Class attributes belong to the class itself they will be shared by all the instances. Such attributes are defined in the class body parts usually at the top, for legibility.

# Write Python code here
class sampleclass:
    count = 0     # class attribute

    def increase(self):
        sampleclass.count += 1

# Calling increase() on an object
s1 = sampleclass()
s1.increase()        
print(s1.count)

# Calling increase on one more
# object
s2 = sampleclass()
s2.increase()
print(s2.count)

print(sampleclass.count)

 

Instance Attributes

实例属性,属于每个具体的实例,

vars 只显示实例自身的属性

dir 除了显示实例自身的属性,还是显示其类的属性。

Unlike class attributes, instance attributes are not shared by objects. Every object has its own copy of the instance attribute (In case of class attributes all object refer to single copy).

To list the attributes of an instance/object, we have two functions:-
1. vars()– This function displays the attribute of an instance in the form of an dictionary.
2. dir()– This function displays more attributes than vars function,as it is not limited to instance. It displays the class attributes as well. It also displays the attributes of its ancestor classes.

# Python program to demonstrate
# instance attributes.
class emp:
    def __init__(self):
        self.name = 'xyz'
        self.salary = 4000

    def show(self):
        print(self.name)
        print(self.salary)

e1 = emp()
print("Dictionary form :", vars(e1))
print(dir(e1))

 

How Python class attributes work

https://www.pythontutorial.net/python-oop/python-class-attributes/

访问实例属性,首先访问实例自身的属性列表, 如果没有找到则去class中查找。

When you access an attribute via an instance of the class, Python searches for the attribute in the instance attribute list. If the instance attribute list doesn’t have that attribute, Python continues looking up the attribute in the class attribute list. Python returns the value of the attribute as long as it finds the attribute in the instance attribute list or class attribute list.

However, if you access an attribute, Python directly searches for the attribute in the class attribute list.

class Test:
    x = 10

    def __init__(self):
        self.x = 20


test = Test()
print(test.x)  # 20
print(Test.x)  # 10

 

When to use Python class attributes

https://www.pythontutorial.net/python-oop/python-class-attributes/

保存类常量, 这个对于所有的实例都是一致的,不变的。

1) Storing class constants

Since a constant doesn’t change from instance to instance of a class, it’s handy to store it as a class attribute.

For example, the Circle class has the pi constant that is the same for all instances of the class. Therefore, it’s a good candidate for the class attributes.

 

跟踪所有实例。

2) Tracking data across of all instances

The following adds the circle_list class attribute to the Circle class. When you create a new instance of the Circle class, the constructor adds the instance to the list:

class Circle:
    circle_list = []
    pi = 3.14159

    def __init__(self, radius):
        self.radius = radius
        # add the instance to the circle list
        self.circle_list.append(self)

    def area(self):
        return self.pi * self.radius**2

    def circumference(self):
        return 2 * self.pi * self.radius


c1 = Circle(10)
c2 = Circle(20)

print(len(Circle.circle_list))  # 2

 

统一管理实例的默认值

3) Defining default values

Sometimes, you want to set a default value for all instances of a class. In this case, you can use a class attribute.

The following example defines a Product class. All the instances of the Product class will have a default discount specified by the default_discount class attribute:

class Product:
    default_discount = 0

    def __init__(self, price):
        self.price = price
        self.discount = Product.default_discount

    def set_discount(self, discount):
        self.discount = discount

    def net_price(self):
        return self.price * (1 - self.discount)


p1 = Product(100)
print(p1.net_price())
 # 100

p2 = Product(200)
p2.set_discount(0.05)
print(p2.net_price())
 # 190

 

Check if a Python Object Has Attributes

https://www.delftstack.com/howto/python/check-if-a-python-object-has-attributes/

使用 hasattr 测试属性是否存在。

class Cake:
    best_cake = "Choco Lava"
    best_flavor = "Vanilla"
    cost = 2500
    
cake_object = Cake()
print(hasattr(Cake, 'best_cake'))

使用getattr访问属性值。

class Cake:
    best_cake = "Choco Lava"
    best_flavor = "Vanilla"
    cost = 2500
    
cake_object = Cake()
print(hasattr(Cake, 'best_cake'))

 

posted @ 2022-02-11 23:52  lightsong  阅读(245)  评论(0)    收藏  举报
千山鸟飞绝,万径人踪灭