Python static methods, class methods, properties, methods

Static method

After using the static method, equivalent to the following relations functions and classes cut off, its role is equivalent to class following a separate function, not automatically pass parameters self.

class people:
.....
  @staticmethod
  def xxx():
    pass

  

Class Methods

Can access only class variables, instance variables can not be accessed.

@classmethod

  

Dog class: 
	name = "black" 
	DEF the __init __ (Self, name): 
		the self.name name = 

	@classmethod 
	DEF HIT (CLS): 
		Print ( "% S"% (cls.name)) 


D1 = Dog ( "florets" ) 
d1.hit () 

# output 
black

  

 

Properties Methods

One way to become a static properties, call time does not need parentheses (d1.hit).

Dog class: 
	DEF the __init __ (Self, name): 
		the self.name name = 

	@Property 
	DEF HIT (Self): 
		Print ( "% S"% (the self.name)) 



D1 = Dog ( "florets") 
d1.hit 

# output 
flowers

  

So how do the parameters passed to the method attribute?

You can see the code below, need to add @ hit.setter decoration (must be written in @property below), and the two function names consistent.

class dog:
	def __init__(self,name):
		self.name = name
		self.__age = None

	@property
	def hit(self):
		print("%s%s" % (self.name,self.__age))

	@hit.setter
	def hit(self,age):
		print("Set hit input:",age)
		self.__age = age

d1 = dog("小花")
d1.hit
d1.hit = 11
d1.hit

#输出
小花None
Set hit input: 11
小花11

  

  

Since it can pass parameters, then delete the attribute method is also supported.

@hit.deleter
	def hit(self):
		del self.__age

  

 

Guess you like

Origin www.cnblogs.com/endust/p/12325453.html