class MyObject(object): x = 1
def __init__(self): objectNum = 99
def changeNum(self, anotherNum): self.objectNum = anotherNum def showNum(self): print("self.num = ", self.objectNum)
obj = MyObject() obj.showNum() Traceback (most recent call last): File "class.py", line 24, in <module> obj.showNum() File "class.py", line 20, in showNum print("self.num = ", self.objectNum) AttributeError: 'MyObject' object has no attribute 'objectNum'
obj = MyObject() obj.changeNum(10) obj.showNum() >>> self.num = 10
class ExampleClass: def createObjectProperty(self, value): self.newObjectProperty = value
class MyObject(object): x = 1
def __init__(self): self.objectNum = 99
def changeNum(self, anotherNum): self.objectNum = anotherNum def showNum(self): print("self.num = ", self.objectNum)
class MyObject(object): x = 1
def __init__(self): self.objectNum = 99
def changeNum(self, anotherNum): self.objectNum = anotherNum def showNum(self): print("self.num = ", self.objectNum) obj = MyObject() print(MyObject.x) >>> 1
MyObject.x = 100
print(MyObject.x) >>> 100
t1 = MyObject() print(t1.x) >>> 1 t2 = MyObject() print(t2.x) >>> 1 MyObject.x = 1000
print(t1.x) >>> 1000
print(t2.x) >>> 1000 t1.x = 2000
print(t2.x) >>>1000
print(t1.x) >>>2000
print(MyObject.x) >>>1000
t2 = MyObject() t1 = MyObject() print(MyObject.x is t1.x) >>>True print(MyObject.x is t2.x) >>>True print(t2.x is t1.x) >>>True --------------------------------------- t2 = MyObject() t1 = MyObject() t2.x = 10
print(MyObject.x is t1.x) >>>True print(MyObject.x is t2.x) >>>False print(t2.x is t1.x) >>>False -------------------------------------- t2 = MyObject() t1 = MyObject() MyObject.x = 100 t2.x = 10
print(MyObject.x is t1.x) >>>True print(MyObject.x is t2.x) >>>False print(t2.x is t1.x) >>>False
构造函数中定义了类的成员变量,类的成员变量必定是在构造函数中以self.开头的变量!python
成员函数中能够调用成员变量和类变量!成员函数的形参在类的实例调用该函数时传递,成员函数的局部变量在该成员函数内部定义。调用成员函数和调用普通函数同样,只是成员函数由该函数对应的类调用,即须要写成xxxx.func()而不是直接使用func()!
函数