https://cloud.tencent.com/developer/article/1874128
最简单的类定义看起来像这样
class ClassName:
<statement-1>
.
.
.
<statement-N>
类定义与函数定义 (def 语句) 一样必须被调用执行才会起作用
类名中的所有单词首字母要大写,采用驼峰命名法(例 GameCase )的书写方式
class Dog:
pass
class Person:
def introduce(self):
print('My name is %s, I am %d years old' % (self.name, self.age))
Person 类,有一个方法 introduce,有两个属性 name、age
# 对象一
tom = Person()
# 对象属性
tom.name = 'tom'
tom.age = 10
# 对象二
jerry = Person()
# 对象属性
jerry.name = 'jerry'
jerry.age = 20
# 调用对象的方法
tom.introduce()
jerry.introduce()
# 输出结果
My name is tom, I am 10 years old
My name is jerry, I am 20 years old
# 类对象
class person:
pass
print(person)
print(id(person))
# 输出结果
<class '__main__.person'>
140485598521200
打印的就是一个类对象和内存地址
Obj.name
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
有效的属性引用
print(MyClass.i)
print(MyClass.f)
print(MyClass.__doc__)
# 输出结果
12345
<function MyClass.f at 0x10f43f310>
A simple example class
实例化其实就是调用类对象,从而创建一个实例对象
c = MyClass()
创建类的新实例并将此对象分配给局部变量 c
# 实例对象
class person:
pass
# 实例化:类名()
p1 = person()
p2 = person()
p3 = person()
print(p1, id(p1))
print(p2, id(p2))
print(p3, id(p3))
# 输出结果
<__main__.person object at 0x10e42b8b0> 4534220976
<__main__.person object at 0x10e42b880> 4534220928
<__main__.person object at 0x10e42b850> 4534220880
三个 person 类实例对象,分别有自己独立的内存地址
__init__
由此可见,一个类可以有很多个对象,每个对象都有属于自己的属性、方法;
__init__、实例属性、实例方法后续详解
self
如果不懂的话,看看下面代码的输出就知道啦; id() 是用于获取对象的内存地址
class person():
def __init__(self, name):
self.name = name
print(f"init-{self.name} ", id(self))
def test(self):
print(f"test-{self.name} ", id(self))
p1 = person("p1")
print("p1-", id(p1))
print("p1 fun-", id(p1.test))
p2 = person("p2")
print("p2-", id(p2))
print("p2 fun-", id(p2.test))
# 输出结果
init-p1 4435237568
p1- 4435237568
p1 fun- 4435260032
init-p2 4435237472
p2- 4435237472
p2 fun- 4435260032
可以看到,两个实例对象调用的实例方法是同一个内存地址