2022-04-19

WARNING: This article may be obsolete
This post was published in 2022-04-19. Obviously, expired content is less useful to users if it has already pasted its expiration date.
This article is categorized as "Garbage" . It should NEVER be appeared in your search engine's results.

Python OOP

复习repr等魔术方法

🔗 [2021-10-19 - Truxton's blog] https://truxton2blog.com/2021-10-19/

class attributes and instance attributes

参考:🔗 [Class Attributes vs Instance Attributes in Python] https://www.tutorialsteacher.com/articles/class-attributes-vs-instance-attributes-in-python

# 修改自:https://www.tutorialsteacher.com/articles/class-attributes-vs-instance-attributes-in-python

class Student:
    count = 0

    def __init__(self):
        Student.count += 1


print(Student.count)  # 0
print(Student.count)  # 0 
Student()
Student()
print(Student.count)  # 2

私有变量

🔗 [访问限制 - 廖雪峰的官方网站] https://www.liaoxuefeng.com/wiki/1016959663602400/1017496679217440

注意:在class内部仍然可以访问私有变量,即使访问另一个class instance object的私有变量也是可以的

class A(object):
    def __init__(self, var):
        self.__var = var

    def minus(self, another):
        return (self.__var - another.__var)  # 这是允许的


a1 = A(1)
a2 = A(5)
print(a1.minus(a2))  # -4
# print(a1.__var)  # AttributeError: 'A' object has no attribute '__var'


 Last Modified in 2022-06-29 

Leave a Comment Anonymous comment is allowed / 允许匿名评论