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())
输出结果为:
Hello World 12345 ('1', '2', 33) ('张', '三', 33) (1, 2)
如果用 print(x.W) 将会报错:
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'
如果用
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
将会返回输出
('1', '2', 33) ('张', '三', 33) (1, 2)
对于Python,是不是可以任意创建传参,在方法中传入一个address(默认参数),但这里的不能通过对象 p.address 来直接使用,只能在调用 speak 的时候使用
当函数有多个参数时,把变化大的参数放前面,变化小的参数放后面。变化小的参数就可以作为默认参数。
使用默认参数有什么好处?最大的好处是能降低调用函数的难度。
1 class people: 2 # 定义基本属性 3 # 定义私有属性,私有属性在类外部无法直接进行访问 4 # 定义构造方法 5 def __init__(self, n, a, w): 6 self.name = n 7 self.age = a 8 self.__weight = w 9 10 def speak(self,address): 11 self.address = 'lala' 12 print("%s 说: 我 %d 岁。%s" % (self.name, self.age,self.address)) 13 14 p = people('runoob', 10, 30) 15 p.speak("zz")
输出为:
runoob 说: 我 10 岁。lala