The concept of class in Python programming can be compared to the description of a certain type of collection. For example, "human beings" can be regarded as a class, and then the human class is used to define each specific person-you, me, him. etc. as its object. Classes also have attributes and functions. Attributes are some characteristics of the class itself. For example, humans have attributes such as name, height, and weight, and the specific values will vary according to each person; functions are the behaviors that the class can achieve, such as humans have Functions such as eating, walking and sleeping.
The specific form is as follows:
# Example: The concept of class
class Human being:
Name = ' Unnamed' # Member variable
def speak (content): # Member function
Member variable # Someone. Name = "Passenger A"
Someone. Speak ('Hello everyone') # Passer-by A speaks
>>> Hello everyone! #Output
Sample program one (class definition):
>>> class pp: ... pass ... >>> p = pp() >>> print p <__main__.pp instance at 0x00CA77B0> >>>
Python Video Tutorial
"Sample program two (__init__ usage):
Description: __init_ The _ method is run immediately when the object of the class is created. This method is used to initialize the object.
>>> class Person: ... def __init__(self, name): ... self.name = name ... def sayHi(self): ... print 'Hello, my name is', self.name ... >>> p = Person('Swaroop') >>> p.sayHi() Hello, my name is Swaroop >>>
Sample program three (__del__ method):
Explanation: The __del__ method is called when the program exits.
>>> class Person: ... population = 0 ... def __init__(self, name): ... self.name = name ... print '(Initializing %s)' % self.name ... def __del__(self): ... print '%s says bye.' % self.name ... Person.population -= 1 ... ... def howMany(self): ... if Person.population == 1: ... print 'I am the only person here.' ... else: ... print 'We have %d persons here.' % Person.population ... >>> A = Person('aa') (Initializing aa) >>> A.howMany() We have 0 persons here. >>> B = Person('bb') (Initializing bb) >>> B.howMany() We have 0 persons here. >>> ^Z aa says bye. bb says bye.
# Example: Class Definition and Usage
class CAnimal:
name = 'unname' # 成员变量
def __init__(self,voice='hello'): # 重载构造函数
self.voice = voice # 创建成员变量并赋初始值
def __del__(self): # 重载析构函数
pass # 空操作
def Say(self):
print self.voice
t = CAnimal() # 定义动物对象t
t.Say() # t说话
>> hello # 输出
dog = CAnimal('wow') # 定义动物对象dog
dog.Say() # dog说话
>> wow # 输出
# Example: Class inheritance
class CAnimal:
def __init__(self,voice='hello'): # voice初始化默认为hello
self.voice = voice
def Say(self):
print self.voice
def Run(self):
pass # 空操作语句(不做任何操作)
class CDog(CAnimal): # 继承类CAnimal
def SetVoice(self,voice): # 子类增加函数
SetVoice self.voice = voice
def Run(self,voice): # 子类重载函数Run
The above is the detailed content of How to use class in python. For more information, please follow other related articles on the PHP Chinese website!