Python基础--构造函数

亦凉 2022-07-29 09:29 269阅读 0赞

记得吧,Python中有一个关键字叫self。

构造

  1. class FooBar:
  2. def _int_(self):
  3. self.somevar = 42
  4. >>>f = FooBar()
  5. >>>f.somevar
  6. 42

重写

  1. class A:
  2. def hello(self):
  3. print "Hello, I'm A"
  4. class B(A):
  5. def hello(self):
  6. print "Hello, I'm B"
  7. b = B()
  8. b.Hello()
  9. Hello, I'm B

属性

  1. class Rectangle:
  2. def _init_(self):
  3. self.width = 0
  4. self.height = 0
  5. def setSize(sef, size):
  6. self.width, self.height = size
  7. def getSize(self):
  8. return self.width, self.height

使用:

  1. r = Rectangle()
  2. r.width = 10
  3. r.height = 5
  4. r.getSize() #(10, 5)
  5. r.setSize(150, 100) #(150, 100)

Property函数
就是对上面的属性进行包装:

  1. class Rectangle:
  2. def _init_(self):
  3. self.width = 0
  4. self.height = 0
  5. def setSize(sef, size):
  6. self.width, self.height = size
  7. def getSize(self):
  8. return self.width, self.height
  9. size = property(getSize, setSize)

使用:

  1. r = Rectangle()
  2. r.width = 10
  3. r.height = 5
  4. r.size #(10, 5)
  5. r.size(150, 100) #(150, 100)

静态方法
装饰器@

  1. class MyClass:
  2. @staticmethod
  3. def smeth():
  4. print 'This is a static method'

发表评论

表情:
评论列表 (有 0 条评论,269人围观)

还没有评论,来说两句吧...

相关阅读