Skip to content

Commit 1d863b9

Browse files
author
tuntun
committed
Python面向对象:类,类的方法,类方法,静态方法
1 parent fd43729 commit 1d863b9

1 file changed

Lines changed: 34 additions & 7 deletions

File tree

cls.py renamed to method.py

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,45 @@
11
# -*- coding: utf-8 -*-
22

3-
# Python 的cls
3+
# Python面向对象:类,类的方法,类方法,静态方法
44

5-
class demo(object):
6-
def foo(cls):
5+
class Person(object):
6+
def __init__(self):
7+
print('init')
8+
9+
@staticmethod
10+
def sayHello(hi):
11+
if hi is None:
12+
hi = 'hello'
13+
print(hi)
14+
15+
@classmethod
16+
def hi(cls,msg):
17+
print(msg)
718
print(dir(cls))
819

9-
demo = demo()
10-
demo.foo()
20+
# 一般类的方法
21+
def hobby(self,hobby):
22+
print(hobby)
23+
24+
# 调用静态方法,不用实例化
25+
Person.sayHello('hi')
26+
Person.hi('Hi!')
27+
28+
# 实例化类调用普通方法,__init__在这里触发
29+
person = Person()
30+
person.hobby('football')
31+
1132

1233
"""
13-
demo.foo()输出的结果跟dir(demo)的结果一样:
34+
输出:
35+
hi
36+
Hi!
1437
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof_
15-
_', '__str__', '__subclasshook__', '__weakref__', 'foo']
38+
_', '__str__', '__subclasshook__', '__weakref__', 'hi', 'hobby', 'sayHello']
39+
init
40+
football
41+
42+
其中def hi(cls)这个类方法,cls表示类自身,所以输出跟dir(person)是一样的。
1643
1744
classmethod:类方法
1845
staticmethod:静态方法

0 commit comments

Comments
 (0)