1 class MyClass: 2 3 i = 12345 4 5 def __init__(self): 6 self.data = "WOOWOWOWO" 7 8 def f(self): 9 return 'Hello World' 10 11 def New(self,W = '1',N = '2', x = 33): 12 self.W = 'lla is W' 13 self.N = 'lll' 14 return W,N,x 15 16 def x(self,ss = 1,dd = 2): 17 return ss,dd 18 19 x = MyClass() 20 print(x.f()) 21 print(x.i) 22 print(x.New()) 23 print(x.New('张','三')) 24 print(x.x())
The output is:
Hello World 12345 ('1', '2', 33) ( ' Photos ' , ' three ' , 33 ) (1, 2)
If print (xW) will be given:
Traceback (most recent call last): File "E:/PyPrograms/Unit1/Day03/Class_1.py", line 22, in <module> print(x.W) AttributeError: 'MyClass' object has no attribute 'W'
If you use
def New(self,W = '1',N = '2', x = 33): self.W = 'lla is W' self.N = 'lll' return W,N,x def x(self,ss = 1,dd = 2): return ss,dd
It will return output
('1', '2', 33) ( ' Photos ' , ' three ' , 33 ) (1, 2)
For Python, is not to create any parameter passing, passing a address in the method, but this can not be used directly by the object p.address, can only be used when calling speak of
. 1 class people: 2 # defines the basic properties of 3 # define private property, private property can not be directly accessed from outside the class 4 # define constructor . 5 DEF the __init__ (Self, n-, A, W): . 6 the self.name = n- . 7 Self = .age A . 8 Self. __weight = W . 9 10 DEF Speak (Self, address): . 11 self.address = ' Lala ' 12 is Print ( " % S says:% d years old I S% " %(self.name, self.age, self.address)) 13 14 the p-people = ( ' runoob ' , 10, 30 ) 15 p.speak ( " ZZ " )
output:
runoob said: I am 10 years old. lala