Python 基础-1

1、类就是创建对象的模板

类由3个部分构成

类的名称:类名
类的属性:一组数据
类的方法:允许对进行操作的方法(行为)
2、
__init__()方法,在创建一个对象时默认被调用,不需要手动调用
__init__(self)中,默认有1个参数名字为self,如果在创建对象时传递了2个实参,那么__init__(self)中出了self作为第一个形参外还需要2个形参,例如__init__(self,x,y)

__init__(self)中的self参数,不需要开发者传递,python解释器会自动把当前的对象引用传递进去

3、
Python中没有像C++中public和private这些关键字来区别公有属性和私有属性

它是以属性命名方式来区分,如果在属性名前面加了2个下划线'__',则表明该属性是私有属性,否则为公有属性(方法也是一样,方法名前面加了2个下划线的话表示该方法是私有的,否则为公有的)。

4、
私有的属性,不能通过对象直接访问,但是可以通过方法访问
私有的方法,不能通过对象直接访问
私有的属性、方法,不会被子类继承,也不能被访问

一般情况下,私有的属性、方法都是不对外公布的,往往用来做内部的事情,起到安全的作用

类属性

class People(object):
    name = 'Tom'  #公有的类属性
    __age = 12     #私有的类属性

p = People()

print(p.name)           #正确
print(People.name)      #正确
print(p.__age)            #错误,不能在类外通过实例对象访问私有的类属性
print(People.__age)        #错误,不能在类外通过类对象访问私有的类属性

实例属性(对象属性)

class People(object):
    address = '山东' #类属性
    def __init__(self):
        self.name = 'xiaowang' #实例属性
        self.age = 20 #实例属性

p = People()
p.age =12 #实例属性
print(p.address) #正确
print(p.name)    #正确
print(p.age)     #正确

print(People.address) #正确
print(People.name)    #错误
print(People.age)     #错误
5、类方法和静态方法

@classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.
@staticmethod means: when this method is called, we don't pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can't access the instance of that class (this is useful when your method does not use the instance).

@classmethod意思是:

当这个方法被调用时,我们传递类作为第一个参数,而不是那个类的实例(就像我们通常用方法做的那样)。这意味着您可以在该方法内使用该类及其属性,而不是特定的实例。

无论你用哪种方式访问这个方法,它总是绑定到了这个类身上,它的第一个参数是这个类本身(记住:类也是对象)。

@staticmethod意思是:

当这个方法被调用时,我们不会传递类的实例给它(就像我们通常用方法做的那样)。这意味着你可以在一个类中放入一个函数,但你不能访问该类的实例(当你的方法不使用实例时这很有用)。这个方法并不需要依赖对象本身的状态。

区别
(1)实例方法
属于实例的方法 
只能通过 实例名.方法名 调用。 
其可以访问类属性、实例属性,类方法、实例方法、静态方法。

(2) 类方法
属于类的方法 
可以通过 实例名.方法名,也可以 类名.方法名 
其不能访问实例属性和实例方法
(3) 静态方法
和类方法很相似,不同的时候定义时要定义(cls)参数 
可以通过 实例名.方法名,也可以 类名.方法名 

其不能访问实例属性和实例方法

\实例方法类方法静态方法
a = A()a.foo(x)a.class_foo(x)a.static_foo(x)
A不可用A.class_foo(x)A.static_foo(x)

面试题:

classA(object):  
  
deffoo(self,x):  
  
print("executing foo(%s,%s)"%(self,x))  
  
print('self:',self)  
 
@classmethod  
  
defclass_foo(cls,x):  
  
print("executing class_foo(%s,%s)"%(cls,x))  
  
print('cls:',cls)  
 
@staticmethod  
  
defstatic_foo(x):  
  
print("executing static_foo(%s)"%x)  
  
a=A()  
  
print(a.foo(1))  
  
print(a.class_foo(1))  
  
print(a.static_foo(1))  












  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值