公共方法是指可以被其他对象调用的方法。 classMyClass:def__init__(self,name):self.name=namedefpublic_method(self):print('Hello, '+self.name) 1. 2. 3. 4. 5. 6. 在上面的代码中,我们定义了一个名为public_method的公共方法。该方法打印出一个问候语,其中包含了对象的name属性。 步骤3:创建一个...
def static_method(): print("我是一个静态方法") # @classmethod # 类方法,可以直接通过 类型.方法名访问 def class_method(cls): print("我是一个类方法") A.static_method() # A.class_method() # 若不用 @classmethod 修饰,则需要通过创建实例访问方法 a = A() a.class_method() 1. 2. 3....
def public_method(self): print("公有方法") self.__private_method obj = MyClass obj.public_method #输出: #公有方法 #私有方法 obj.__private_method # 报错:AttributeError: 'MyClass' object has no attribute '__private_method' ``` 在上面的代码中,私有方法 "__private_method(" 只能在类内...
class MyClass: def public_method(self): return "This is a public method." def _protected_method(self): return "This is a protected method." def __private_method(self): return "This is a private method." def access_private_method(self): return self.__private_m...
>>> class A(object): #构造方法可能会被派生类继承 def __init__(self): self.__private() self.public() #私有方法在派生类中不能直接访问 def __private(self): print('__private() method in A') #公开方法在派生类中可以直接访问,也可以被覆盖 ...
self._private_method() def _private_method(self): print("这是一个私有方法") 创建一个对象并调用公共方法 obj = MyClass() obj.public_method() 输出结果: 这是一个公共方法 这是一个私有方法 注意:虽然私有方法不能直接访问,但是可以通过类的公共方法间接访问,在上面的例子中,我们通过public_method方法...
class Test_P: def __init__(self): self.public_attribute = 'This is a public attribute.' self._protected_attribute = 'This is a protected attribute.' self.__private_attribute = 'This is a private attribute.' def public_method(self): print('call of public method.') def _protected_me...
1.首行是class 开头,然后类名字+:号结尾 2.类的内部定义各种函数和变量; 3.函数内就封装各种功能。 代码语言:shell 复制 class 类名字: def __init__(self, 参数): self.变量A=""self.变量B=0self.变量C=0.0...代码 def 函数名字(self):...代码...代码 ...
class Base(object): def _secret(self): print("Base secret") def __hide(self): print("Normal __hide") def _Base__hide(self): print("Special _Base__hide") def public(self): print("From public method") self.__hide() print dir(Base()) ...
print(self.__class__) t = Test() t.prt() 以上实例执行结果为: <__main__.Test instance at 0x100771878> __main__.Test 从执行结果可以很明显的看出,self 代表的是类的实例,代表当前对象的地址,而 self.class 则指向类。 self 不是 python 关键字,我们把他换成 runoob 也是可以正常执行的: ...