在Python中,类带有成员函数(方法)、类变量、属性/实例变量(可能还有类方法):
class Employee:
# Class Variable
company = "mycompany.com"
def __init__(self, first_name, last_name, position):
# Instance Variables
self._first_name = first_name
self._last_name = last_name
self._position = position
# Member function
def get_full_name(self):
return f"{self._first_name} {self._last_name}"
通过创建对象的实例
my_employee = Employee("John", "Wood", "Software Engineer")
我们实际上触发了__init__,它将初始化新创建的Employee的实例变量。这意味着_first_name, _last_name和_position是特定my_employee实例的显式参数。
同样,成员函数返回信息或更改特定实例的状态。
现在,在构造函数__init__之外定义的任何变量都被认为是类变量。这些变量在类的所有实例之间共享。
john = Employee("John", "Wood", "Software Engineer")
bob = Employee("Bob", "Smith", "DevOps Engineer0")
print(john.get_full_name())
print(bob.get_full_name())
print(john.company)
print(bob.company)
>>> John Wood
>>> Bob Smith
>>> mycompany.com
>>> mycompany.com
您还可以使用类方法来更改类的所有实例的类变量。例如:
@classmethod
def change_my_companys_name(cls, name):
cls.company = name
现在输入change_my_companys_name()
bob.change_my_companys_name("mynewcompany.com")
将对类Employee的所有实例产生影响:
print(bob.company)
print(john.company)
>>> mynewcompany.com
>>> mynewcompany.com