Python-类和对象
在本教程中,我们将学习Python中的类和对象。
Python是一种面向对象的编程(OOP)语言。
Python中的所有内容都是一个由一些方法和属性(属性)组成的对象。
什么是类?
类是用于创建对象的蓝图。
类由属性(属性)和方法组成。
我们使用Python中的class
关键字创建类。
语法:
class className: # # some code goes here... #
其中,className是类的名称。
命名类的规则
以下是命名类的规则。
类名必须使用大写字母大写,例如" MyAwesomeClass"。
保持班级名称简短而有意义。
请勿以数字开头的班级名称。
不要使用Python关键字来命名类。
什么是对象?
对象是类的实例。
例如,如果类是房屋的蓝图,则对象是使用该蓝图建造的实际房屋。
我们通过在类名后面加上括号来创建类的对象。
语法:
# class class MyAwesomeClass: # # some code goes here... # # object of the class obj = MyAwesomeClass()
添加类属性
我们可以在类内部添加称为类的属性(属性)的变量。
在下面的Python程序中,我们将创建一个具有属性的类。
# class class Awesome: # attribute common to all the objects of this class foo = 0 # objects of the class obj1 = Awesome() obj2 = Awesome()
设置类属性的值
我们使用以下表示法来设置类的所有对象所共有的类属性的值。
ClassName.attr = val
其中," ClassName"是类的名称,而" attr"是类属性。
val是我们分配给class属性的值。
在下面的Python程序中,我们将设置类的所有对象所共有的class属性的值。
# class class Awesome: # attribute common to all the objects of this class foo = 0 # value of foo before any object print("before: foo =", Awesome.foo) # object of the class obj1 = Awesome() # add 1 to foo Awesome.foo = Awesome.foo + 1 print("after obj1: foo =", Awesome.foo) # object of the class obj2 = Awesome() # add 1 to foo via obj2 obj2.foo = obj2.foo + 1 print("after obj2: foo =", obj2.foo)
我们将获得以下输出。
before: foo = 0 after obj1: foo = 1 after obj2: foo = 2
添加类方法
我们可以使用def
关键字为类添加方法。
类方法非常类似于函数。
在下面的Python程序中,我们将greetings
方法添加到Awesome
类中。
# class class Awesome: # attribute common to all the objects of this class foo = 0 # method common to all the objects of this class def greetings(self): print("Hello World") # object of the class obj = Awesome() # calling class method obj.greetings()
上面的代码将打印" Hello World"。
注意!该类的每个方法的第一个参数是" self"。
" self"关键字引用该类的当前对象,用于从类内部访问该类的属性和方法。
通过对象调用类的方法时,我们不必传递" self"作为参数。
使用self访问属性和方法
在下面的Python程序中,我们使用self
关键字访问类属性和方法。
# class class Awesome: # attribute common to all the objects of this class foo = 0 # methods common to all the objects of this class def greetings(self): print("Hello World") def output(self): # calling greetings method self.greetings() # printing foo value print("foo from Awesome class:", self.foo) # object of the class obj = Awesome() # updating foo value obj.foo = 10 # calling class method obj.output()
上面的代码将打印以下输出。
Hello World foo from Awesome class: 10
说明:
在上面的示例中,我们首先创建Awesome
类的对象。
然后,使用obj对象来更新foo的值。
然后,我们调用Awesome类的output()
方法。
在output()方法内部,我们使用self关键字调用greetings()方法。greetings()
方法输出字符串" Hello World"。
最后,使用" self"关键字来打印" foo"属性的值。