class definition
In Python, classes are defined by the class keyword, and the class name starts with a capital letter
>>>class Person(object): #所有的类都是从object类继承
pass #pass先不做任何处理,先跳过,为了防止语法错误
Create class properties
>>> class Person(object):
address = 'Earth' #类的属性直接在类内部定义,当实例属性和类属性重名时,实例属性优先级高
def __init__(self, name):
self.name = name
>>> Person.address #直接通过类.属性可以访问
'Earth'
>>>p1=Person('A')
>>>p1.address #通过创建类的实例,也可以通过实例.属性访问
'Earth'
>>> Person.address='KKKK' #类的属性可以动态修改
>>> Person.address
'KKKK'
>>>p1.address #类的属性一经修改,所有访问的属性值也随之更改
'KKKK'
instance creation
To create an instance, use the class name + (), which is similar to a function call:
E.g:
>>> class Person(object):
pass
>>> p1 = Person() #创建实例
>>> p1.name = 'Bart' #创建实例属性
>>> p2 = Person()
>>> p2.name = 'Adam'
Initialize instance properties
>>> class Person(object):
class=1 #定义类属性
def __init__(self, name,age):
#__init__(self,属性1,属性2....):self代表实例,通过self访问实例对象的变量和函数
self.name = name
self.__age=age
#实例的私有属性无法从外部访问,但是,从类的内部是可以访问的
#定义实例方法
def get_name(self):
return self.__age
#实例方法,定义在类内部,可以访问实例的私有属性__age
#定义类方法
@classmethod
def how_many(cls):
#通过@classmethod标记类方法,类方法的第一个参数为cls,cls.class相当于Person.class
return cls.class
#类方法中无法调用任何实例的变量,只能获得类引用
>>> p1 = Person('Bob',12)
>>> print (p1.get_age())
Notice:
The difference between underscore and double underscore:
Starting with a single underscore _foo represents a class attribute that cannot be directly accessed. It needs to be accessed through the interface provided by the class. Then the name starting with _ will not be imported, that is, it cannot be imported with from xxx import *, unless the module or package The __all__ list in contains them explicitly;
__foo starting with a double underscore represents a private member of the class, which can only be accessed by the class itself, and its subclass objects cannot access this data either.