1. Define attributes directly in the class
Define the attributes of the class. Of course, the simplest and most direct way is to define them in the class, for example:
class UserInfo(object): name='两点水'
2. Define attributes in the constructor
The name suggests that the attributes are defined when constructing the object.
class UserInfo(object): def __init__(self,name): self.name=name
3. Attribute access control
In Java, there are public (public) properties and private (private) properties, which can control access to properties. So is there any attribute access control in Python?
Generally, we will use __private_attrs starting with two underscores to declare that the attribute is private and cannot be used or directly accessed outside the class. When using self.__private_attrs in a method inside a class.
Why can we only say that under normal circumstances? Because in fact, Python does not provide functions such as private attributes. However, Python's access control of attributes depends on the programmer's awareness. Why do you say that? Take a look at the following example:
Look at the picture carefully, why do you say that the double underline is not a real private attribute? Let's take a look at the following example and use the following example to verify:
#!/usr/bin/env python # -*- coding: UTF-8 -*- class UserInfo(object): def __init__(self, name, age, account): self.name = name self._age = age self.__account = account def get_account(self): return self.__account if __name__ == '__main__': userInfo = UserInfo('两点水', 23, 347073565); # 打印所有属性 print(dir(userInfo)) # 打印构造函数中的属性 print(userInfo.__dict__) print(userInfo.get_account()) # 用于验证双下划线是否是真正的私有属性 print(userInfo._UserInfo__account)
The output result is as shown below:
Next Section