# 示例
class ClassName:
<statement-1>
.
.
.
<statement-N>
class A:
a = 14
b = 12
print(A().a)
# 14
class A:
# 在构造方法中隐式的定义属性:
def __init__(self):
self.a = 13
self.b = 12
print(A().a)
# 13
class A:
def __init__(self,a,b):
self.a = a
self.b = b
print(A(11,12).a)
# 11
class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
.
.
<statement-N>
#类定义
class people:
#定义基本属性
name = ''
age = 0
#定义私有属性,私有属性在类外部无法直接进行访问
__weight = 0
#定义构造方法
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s 说: 我 %d 岁。" %(self.name,self.age))
#单继承示例
class student(people):
grade = ''
def __init__(self,n,a,w,g):
#调用父类的构函
people.__init__(self,n,a,w)
self.grade = g
#覆写父类的方法
def speak(self):
print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))
#另一个类,多重继承之前的准备
class speaker():
topic = ''
name = ''
def __init__(self,n,t):
self.name = n
self.topic = t
def speak(self):
print("我叫 %s,我是一个演说家,我演讲的主题是 %s"%(self.name,self.topic))
#多重继承
class sample(speaker,student):
a =''
def __init__(self,n,a,w,g,t):
student.__init__(self,n,a,w,g)
speaker.__init__(self,n,t)
test = sample("Tim",25,80,4,"Python")
test.speak() #方法名同,默认调用的是在括号中参数位置排前父类的方法
s = student("Tim",12,180)
super(student,s).speak()
# Tim 说: 我 12 岁
class object:
__doc__: str | None
__dict__: dict[str, Any]
__module__: str
__annotations__: dict[str, Any]
@property
def __class__(self: Self) -> type[Self]: ...
# Ignore errors about type mismatch between property getter and setter
@__class__.setter
def __class__(self, __type: type[object]) -> None: ... # type: ignore # noqa: F811
def __init__(self) -> None: ...
def __new__(cls: type[Self]) -> Self: ...
# N.B. `object.__setattr__` and `object.__delattr__` are heavily special-cased by type checkers.
# Overriding them in subclasses has different semantics, even if the override has an identical signature.
def __setattr__(self, __name: str, __value: Any) -> None: ...
def __delattr__(self, __name: str) -> None: ...
def __eq__(self, __o: object) -> bool: ...
def __ne__(self, __o: object) -> bool: ...
def __str__(self) -> str: ... # noqa Y029
def __repr__(self) -> str: ... # noqa Y029
def __hash__(self) -> int: ...
def __format__(self, __format_spec: str) -> str: ...
def __getattribute__(self, __name: str) -> Any: ...
def __sizeof__(self) -> int: ...
# return type of pickle methods is rather hard to express in the current type system
# see #6661 and https://docs.python.org/3/library/pickle.html#object.__reduce__
def __reduce__(self) -> str | tuple[Any, ...]: ...
if sys.version_info >= (3, 8):
def __reduce_ex__(self, __protocol: SupportsIndex) -> str | tuple[Any, ...]: ...
else:
def __reduce_ex__(self, __protocol: int) -> str | tuple[Any, ...]: ...
def __dir__(self) -> Iterable[str]: ...
def __init_subclass__(cls) -> None: ...