1. class Date:
  2. """方法一:使用类方法""" """达到多个构造函数"""
  3. # Primary constructor
  4. def __init__(self, year, month, day):
  5. self.year = year
  6. self.month = month
  7. self.day = day
  8. # Alternate constructor
  9. @classmethod #可以直接除了使用 __init__() 方法外,还有其他方式可以初始化它。
  10. def today(cls): # 不传参
  11. t = time.localtime()
  12. return (t.tm_year, t.tm_mon, t.tm_mday)
  13. print(Date.today()) # 类调用
  14. # (2022, 1, 2)
  15. class newDate(Date): # 可以继承
  16. pass
  17. print(newDate.today()) #
  18. # (2022, 1, 2)
  1. class Book(object):
  2. def __init__(self, title):
  3. self.title = title
  4. @classmethod
  5. def create(cls, title):
  6. book = cls(title) # 传参数必须转化
  7. return book
  8. book1 = Book("python")
  9. book2 = Book.create("python and django")
  10. print(book1.title)
  11. print(book2.title)

类方法调用静态方法,可以让cls代替类,静态调用静态方法

  1. class Foo(object):
  2. X = 1
  3. Y = 2
  4. @staticmethod
  5. def averag(*mixes):
  6. return sum(mixes) / len(mixes)
  7. @staticmethod
  8. def static_method():
  9. return Foo.averag(Foo.X, Foo.Y)
  10. @classmethod
  11. def class_method(cls):
  12. return cls.averag(cls.X, cls.Y)
  13. foo = Foo()
  14. print(foo.static_method())
  15. print(foo.class_method())

静态方法不受类的影响
类方法:与cls有关
实例方法:与self有关

  1. class Dog():
  2. @classmethod
  3. def formal_name(cls):
  4. return cls.__name__.lower()
  5. @staticmethod
  6. def forever_name():
  7. return "dog"
  8. class Husky(Dog):
  9. pass
  10. print(Husky.formal_name(),Husky.forever_name())
  11. #husky dog