Python class

Functions decorated with @classmethod are executed in the class, not in the instance.
@staticmethod Static method: handles some functions that are related to the class but do not require the participation of instances and classes at runtime.

python class

1. Definition:
Example:

class Bird(object):
  have_feather = True
  reproduction = 'oviparous'
  def greet(self):             ## self代表了一个对象,对象拥有类的所有性质
    return "hello"

object: indicates that this class has no parent class
have_feather, reproduction: is the attribute of the class
greet: is the method of the class

2. Class reference:
There are two ways to refer to a class, attribute reference and instantiation, the following comparison.
1 Introduction:

if __name__ == "__main__":
    ##  属性引用
    f = Bird.have_feather 
    print f
    ret = Bird().greet()
    print ret
    ##  类的实例化
    sparrow = Bird()
    print sparrow.have_feather
    print sparrow.greet()

Output:
True
hello
True
hello

2) Contrast

if __name__ == "__main__":
    print Bird.have_feather          #True
    ## 属性引用 
    ## 改变类中的属性的值,类中的属性值改变,类改变后再创建的实例--->实例的属性也是改变后的。
    Bird.have_feather = False 
    print Bird.have_feather          #False
    bird = Bird()
    print bird.have_feather          #False
    Bird.have_feather = True
    ## 类的实例化 
    ## 对实例中的属性进行操作,不影响类的属性,也不会影响其他实例中该属性的值。
    bird.have_feather = Fales
    print bird.have_feather          #False
    print Bird.have_feather          #True
    bird2 = Bird()
    print bird2.have_feather         #True

输出:
True
False
False
False
True
True

3) Create a class init with an initial state

class Bird(object):
  def __init__(self,extend={'can_run':False,'direction':'N','distance':0}):
    self.extend = extend
    self.can_run = extend['can_run']
    self.direction = extend['direction']
    self.distance = extend.get('distance')
  can_fly = True
  run_distance = 0
  run_direction = ''
  have_feather = True
  reproduction = 'oviparous'
  def run(self,others=0):                ## 这里run方法还有一个外部参数others,默认值为0
    can_run = self.can_run
    if can_run is True:
      self.run_direction = self.direction
      self.run_distance += self.distance+others
      print "can"
    else:
      self.run_direction = 'stop'
      self.run_distance += 0
      print "cann't"
  def get_run_info(self):
    return self.run_direction,self.run_distance

Creating a class with an initial state can be achieved through the init method. The instantiation of the
class will automatically call the init method for the newly created instance of the class.
Above, each call of the run method in the Bird class will modify the two attributes of the object, run_distance and run_direction.
The object here can actually be seen as an instance of a class.

if __name__ == "__main__":
  extend = {'can_run':True,'direction':'N','distance':5}
  ## 用类的实例
  sparrow = Bird(extend)
  sparrow.run()                ## run方法让sparrow实例的属性run_distance 、run_direction发生了变化
  print sparrow.get_run_info() 
  ## 用属性引用的方式调
  Bird(extend).run(-10)        ## 这样会有问题,因为run方法是通过self让对象的属性改变,但这里没有定义对象。×
  print Bird().get_run_info()  ## ×

Output:
can
('N',5)
can
(", 0)

3. Class Inheritance - Subclass
1) The derived class (subclass) must be in the same scope as the base class (parent class).
Example:
Define a class Chicken that inherits the Bird class without initialization.
Define a class Ostrich integrated Bird class, with initialization.

class Chicken(Bird):
  can_fly = False             ## 对Bird 类的属性进行了改写
  def cook(self,mod=''):
    return "delicious {} chicker".format(mod)

## Chicken 子类没有__init__ 则仍通过父类Bird()的__init__初始化
## Ostrich 子类有 __init__ 会通过Ostrich()类的__init__初始化,而不是Bird父类。
## 所以如果父类对象的属性会被使用需要在子类中重新定义一遍。

class Ostrich(Bird):
  def __init__(self,extend={'food':'rice'}):
    self.extend = extend
    self.food = extend['food']
    self.can_run = extend['can_run']          ##    如果还要使用父类的属性,或
    self.direction = extend['direction']      ## 使用父类的方法时,父类的属性在
    self.distance = extend.get('distance')    ## 父类的方法中被使用。都需要在init
                                              ## 中,接收进self定义
  def eat(self):
    self.food=self.extend['food']
  def get_eat_info(self):
    return self.food

Create an instance of Chicken class, it will get the properties and methods of Bird class.

if __name__ == "__main__":
  sparrow = Chicken()
  print sparrow.can_fly        ## 子类中重新定义了父类的属性
  print sparrow.have_feather   ## 子类继承父类中的属性
  print sparrow.reproduction    
  sparrow.run()                ## 子类中继承的父类中的方法
  print sparrow.get_run_info() 
  extend = {'food':'grass','can_run':True,'direction':'N','distance':5}
  sparrow2 = Chicken(extend)
  sparrow2.run()
  print sparrow2.get_run_info()
  print "--------------------------"
  extend = {'food':'grass','can_run':True,'direction':'N','distance':5}
  ostrich = Ostrich(extend)
  ostrich.eat()                 ## 子类自己的方法
  print ostrich.get_eat_info()  
  print ostrich.reproduction    ##reproduction是Ostrich父类Bird中的属性
  ostrich.run()                 ## run()Ostrich 父类Bird中的方法。 
  print ostrich.get_run_info()

Output:
False
True
oviparous
cann't
('stop', 0)
can
('N', 5)


grass
oviparous
can
(‘N’, 5)

2) Multiple inheritance - not recommended to use lightly Rules for
parsing class attributes: depth first, left to right

class A(object):
  def __init__(self):
    print "I'm A"
  ab = 'a'

class B(object):
  def __init__(self):
    print "I'm B"
  ab = 'b'

class A2(A):
  def __init__(self):
    print "I'm A2"
  a2 = 'a2'
if __name__ == "__main__":
  c = C()
  print c.ab
## A B都有ab属性,C(A,B)
I'm A
a
## A B都有ab属性,C(B,A)
I'm B
b
## A B都有ab属性 ,A2(A),C(B,A,A2)
## 无法建立一致的方法解析 ×
TypeError: Error when calling the metaclass bases
    Cannot create a consistent method resolution
order (MRO) for bases B, A, A2
## A B都有ab属性 ,A2(A),C(B,A2,A)
I'm B
b

4. Supplement: the usage of self
Above, in the eat method of the People class, the attribute food of this class can be called by means of self.food.
Similarly, it can also be called by means of self.eat() and self.get_eat_info(). methods in this class.

class People(Bird):
  def __init__(self,extend):
    self.extend = extend
  food = ''
  def eat(self):
    self.food=self.extend['food']
  def get_eat_info(self):
    return self.food
  def three_meals(self):
    for times in range(3):
      self.eat()
      print self.get_eat_info()
if __name__ == "__main__":
  extend = {'food':'rice'}
  xiaoming = People(extend)
  xiaoming.three_meals()

Output:
rice
rice
rice

Self is actually the representation of the instance of the class inside the class, that is to say, in the eat method, self.food=… actually modifies
the . Explain with a piece of code:

if __name__ == "__main__":
  extend = {'food':'rice'}
  xiaoming = People(extend)
  xiaoming.eat()
  print xiaoming.get_eat_info()    ## rice
  print xiaoming.food              ## rice

Output:
rice
rice

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325868367&siteId=291194637