Home >Backend Development >Python Tutorial >Introduction to instantiation of classes

Introduction to instantiation of classes

零下一度
零下一度Original
2017-07-20 21:06:142827browse

1. Define a class

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.

2. Self represents an instance, not a class

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 &#39;__main__.Dog&#39;>

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.

3. Create instance objects

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

4. Access attributes 

You can use the dot (.) to access the properties of an object

# 通过 d.方法   来访问属性
d.eat(&#39;beaf&#39;)

#输出
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn