Python object-oriented(3)

Class attribute

As the name implies, the attributes owned by a class object are shared by all instance objects of the
class and can be accessed by class objects and instance objects.

class Gun(object):
	length = 10

wuzi = Gun()
print(Gun.length)
print(wuzi.length)

Both output is 10

Modify class attributes

At this time, you cannot use the instance object to modify the class attribute. If you still use the instance object to modify the class attribute, it is equivalent to creating a new instance attribute by yourself without modifying the class attribute. The only way is to directly modify the class attribute.

Class method

Class methods are generally used to obtain class objects, often used with class attributes

class Gun(object):
	__length = 10
	
	@classmethod
	def get_length(cls):
		return cls.__length

Note that at this time self is changed to cls, and there is a decorator @classmethod

Static method

No need to write cls/self
can be accessed through instance objects and class objects, in order to reduce memory consumption

class Gun(object):
	__length = 10
	
	@staticmethod
	def method(cls):
		print('我是静态方法')
Gun.method()
wuzi = Gun()
wuzi.method()

At this time, the output is my static method

Guess you like

Origin blog.csdn.net/weixin_48445640/article/details/108815240