Home >Backend Development >Python Tutorial >Introduction to instantiation of classes
class Dog(object): # 定义class def __init__(self, name): # 构造函数,构造方法 == 初始化方法 self.name = name # d.name = name 类的属性 / 成员变量 def say_hi(self): # 类的方法 print("Hello, I am a dog. My name is", self.name) def eat(self, food): print("%s is eating %s." % (self.name, food)) d = Dog("xiaohei") # Dog(d,"xiaohei") d == self # d 实例化的对象即实例,类中的self相当于实例 d.say_hi() # d.say_hai(d) d.eat('beaf')
The first method __init__() method is a special method, called It is called the constructor or initialization method of the class. This method will be called when an instance of this class is created.
self represents the instance of the class. self is required when defining the method of the class. Yes, although it is not necessary to pass in the corresponding parameters when calling.
There is only one special difference between class methods and ordinary functions - —They must have an additional first parameter name, which by convention is self.
class Dog(object): def prt(self): print(self) print(self.__class__) d = Dog() print(d) print("-------------") d.prt() #输出 <__main__.Dog object at 0x000001DDBD10C5F8> ------------- <__main__.Dog object at 0x000001DDBD10C5F8> <class '__main__.Dog'>
It can be clearly seen from the execution results that self represents an instance of the class and represents the address of the current object, while self.class points to the class.
The keyword new is generally used to instantiate classes in other programming languages, but in Python it is not Without this keyword, class instantiation is similar to function calling.
# 创建一个Dog类的对象 d = Dog("xiaohei")
The instantiated object is also called: instance
You can use the dot (.) to access the properties of an object
# 通过 d.方法 来访问属性 d.eat('beaf') #输出 xiaohei is eating beaf.
The above is the detailed content of Introduction to instantiation of classes. For more information, please follow other related articles on the PHP Chinese website!