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()!
函數