num = 100
name = "Python"
print(type(num))
print(type(name))
class Student(object):
def study(self):
print("疯狂的学习中")
s1 = Student()
print(s1)
s1.study()
定义属性和使用属性
class Student(object):
def __init__(self):
self.name = None
self.score = 0
def study(self):
print(f"{self.name}疯狂的学习中, 成绩为{self.score}分")
s1 = Student()
s1.name = "张三"
s1.score = 89
s1.study()
s2 = Student()
s2.name = "李四"
s2.score = 90
s2.study()
self 是什么
class Student(object):
def __init__(self):
self.name = None
self.score = 0
def study(self):
print(f"{self.name}疯狂的学习中, 成绩为{self.score}分")
print(f"self的地址是{id(self)}")
def show(self):
print(f"姓名: {self.name}, 分数: {self.score}")
s1 = Student()
s1.name = "张三"
s1.score = 89
s1.study()
print("id(s1) = ", id(s1))
s2 = Student()
s2.name = "李四"
s2.score = 90
s2.study()
print("id(s2) = ", id(s2))
s3 = s2
print("id(s3) = ", id(s3))
构造函数
class Student(object):
def __init__(self, name, score, gender="女"):
self.name = name
self.score = score
self.gender = gender
self.money = None
def study(self):
print(f"{self.name}疯狂的学习中, 成绩为{self.score}分, 性别{self.gender}")
s1 = Student("张三", 100)
s1.study()
s2 = Student("李四", 100)
s2.study()
s3 = Student("王五", 33, "男")
s3.study()
from math import pi
class Circle(object):
def __init__(self, radius=1):
self.radius = radius
def getPerimeter(self):
return self.radius*2*pi
def getArea(self):
return self.radius**2*pi
circle1 = Circle()
print(circle1.radius)
print(circle1.getPerimeter())
print(circle1.getArea())
__str__和属性私有
class Student(object):
def __init__(self, name, score, gender="女"):
self.name = name
self.score = score
self.gender = gender
self.__nick_name = "小小"
def study(self):
print(f"{self.name}疯狂的学习中, 成绩为{self.score}分, 性别{self.gender}")
def __str__(self):
return f"姓名 {self.name}, 成绩{self.score}"
s1 = Student("张三", 100)
s2 = Student("李四", 100)
print(s1)
print(s2)
|