首页 > 其他分享 >CS50P: 8. Object-Oriented Programming

CS50P: 8. Object-Oriented Programming

时间:2024-07-24 09:21:06浏览次数:8  
标签:__ name house self Object Programming Oriented student def

Object-Oriented Programming

turple

A tuple is a sequence of values. Unlike a list, a tuple can’t be modified.

can't be modified: tuple object does not support item assignment不能赋值

Like x, y, z

def main():
    name, house = get_student()
    print(f"{name} from {house}")
def get_student():
    name = input("Name: ")
    house = input("House: ")
    return name, house
if __name__ == "__main__":
    main()

line 7 return a turple with 2 elements,返回的是一个值

turple & index:

def main():
    student = get_student()
    print(f"{student[0]} from {student[1]}")
def get_student():
    name = input("Name: ")
    house = input("House: ")
    return (name, house)

list

def main():
    student = get_student()
    if student[0] == "Padma":
        student[1] = "Ravenclaw"	#可修改
    print(f"{student[0]} from {student[1]}")
def get_student():
    name = input("Name: ")
    house = input("House: ")
    return [name, house]

dict

def main():
    student = get_student()
    if student["name"] == "Padma":
        student["house"] = "Ravenclaw"
    print(f"{student['name']} from {student['house']}")
def get_student():
    student = {}
    student["name"] = input("Name: ")
    student["house"] = input("House: ")
    return student

line 5 的 'name' 必须用单引号括,因为 print(f" ")

line 7 ~10 :

name = input("Name: ")
house = input("House: ")
return {"name": name, "house": house}

classes

Classes are a way by which, in object-oriented programming, we can create our own type of data and give them names.

python’s documentation of classes

class is like bluprint of a house, object is like a house

create new data type

class Student:
    ... # i will come back to implementa this later

create objects from classes

def get_student():
    student = Student()	# create objects/instance
    student.name = input("Name: ")  # . inside the student
    student.house = input("House: ")
    return student

. access attributes of this variable student of class Student

standardize

lay some groundwork for the attributes that are expected inside an object whose class is Student

define a class == get a function: eg. Student可以当作函数

def get_student():
    name = input("Name: ")
    house = input("House: ")
    student = Student(name, house)
    return student

methods

classes come with certain methods/functions inside of them and we can define

_init_

initialize the contents of an object from a class, we define this method

class Student:
    def __init__(self, name, house):
        self.name = name
        self.house = house
def main():
    student = get_student()
    print(f"{student.name} from {student.house}")
def get_student():
    name = input("Name: ")
    house = input("House: ")
    student = Student(name, house)  # construct call, will goto def __init__
    return student

def __init__ : create a function within class Student, called a “method”

self gives us access to the current object that was just created

self.name = name : add variables to objects like add values to keys in dict

line 11 student = Student(name, house) python will call _init_ for us, 在这一步就已经分配内存

_init_ 只会执行一次

_str_

a specific function by which you can print the attributes of an object

class Student:
    def __init__(self, name, house):
        if not name:
            raise ValueError("Missing name")    
        if house not in ["Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin"]:
            raise ValueError("Invalid house")
        self.name = name
        self.house = house
    def __str__(self):
        return f"{self.name} from {self.house}"
def main():
    student = get_student()
    print(student)

our own methods

class Student:
    def __init__(self, name, house, patronus):
        if not name:
            raise ValueError("Missing name")   
        if house not in ["Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin"]:
            raise ValueError("Invalid house")
        self.name = name
        self.house = house  
        self.patronus = patronus
    def __str__(self):
        return f"{self.name} from {self.house}"
    def charm(self):
        match self.patronus:
            case "Stag":
                return "

标签:__,name,house,self,Object,Programming,Oriented,student,def
From: https://www.cnblogs.com/chasetsai/p/18320065

相关文章

  • 鸿蒙HarmonyOS开发:@Observed装饰器和@ObjectLink装饰器:嵌套类对象属性变化
    文章目录一、装饰器二、概述三、限制条件四、装饰器说明五、Toggle组件1、子组件2、接口3、ToggleType枚举4、事件六、示例演示1、代码2、效果一、装饰器@State装饰器:组件内状态@Prop装饰器:父子单向同步@Link装饰器:父子双向同步@Provide装饰器和@Consume装饰器:与......
  • selenium ValueError: Timeout value connect was <object object at 0x0000022273034
    Traceback(mostrecentcalllast):File"E:\01_pycharmProject\hengyi\img_split\get_urls_bySel.py",line24,indriver=webdriver.Chrome(options=option)原因:selenium与urllib版本不匹配原selenium版本为4.1.3,urllib为2.2.2,并将chromedriver.exe更新到python/sc......
  • SubScene不是Scene,是GameObject
    有人问我如何通过Editor代码往SubScene里面加东西?说在Scene相关的类里面都没有找到合适的函数。找不到就对了,因为SubScene不是Scene,是GameObject。可以试试这样的操作:建立一个GameObject给这个GameObject添加一个叫SubScene的脚本在脚本的SceneAsset中,选择一个之前保存过的......
  • 视频汇聚平台EasyCVR启动出现报错“cannot open shared object file”的原因排查与解
    安防视频监控EasyCVR安防监控视频系统采用先进的网络传输技术,支持高清视频的接入和传输,能够满足大规模、高并发的远程监控需求。EasyCVR平台支持多种视频流的外部分发,如RTMP、RTSP、HTTP-FLV、WebSocket-FLV、HLS、WebRTC、fmp4等,这为其在各种复杂环境下的部署提供了便利。有用......
  • [Java源码]Object
    ClassObjectjava.lang.ObjectpublicclassObjectClassObjectistherootoftheclasshierarchy.EveryclasshasObjectasasuperclass.Allobjects,includingarrays,implementthemethodsofthisclass.Since:JDK1.0SeeAlso:ClassConstructorSumm......
  • com.alibaba.fastjson.JSONObject cannot be cast to xxx
    问题描述:通过redis读取的缓存对象用Object去接,因为我们已经知道他具体是什么类型了,所以接来的对象直接转换,报了上述错误。这里其实我们已经对该实体类完成了序列化与反序列化。 publicclassLoginUserimplementsSerializableLoginUserloginUser=redisCache.getCache......
  • SwiftUI中全局EnvironmentObject的使用和注意事项,实现多界面共享数据
    SwiftUI的@EnvironmentObject是一个强大的工具,它允许你在多个视图之间共享数据(使用一个可观察对象)。当你有一个复杂的视图层次结构,并且需要在没有直接连接的视图之间共享相同的可观察对象时,它特别有用。创建ObservableObject协议类要使用环境对象,首先需要创建一个符合Obse......
  • 交叉验证函数返回“未知标签类型:(array([0.0, 1.0], dtype=object),)”
    以下是完整的错误:`---------------------------------------------------------------------------ValueErrorTraceback(mostrecentcalllast)CellIn[33],line21gnb=GaussianNB()---->2cv=cross_val_score(gnb,X_train......
  • Self-supervised Video Object Segmentation by Motion Grouping
    Self-supervisedVideoObjectSegmentationbyMotionGrouping文章目录Self-supervisedVideoObjectSegmentationbyMotionGrouping前言摘要1引言2相关工作3方法3.1流分割架构3.2自监督时间一致性损失3.3讨论4.实验设置4.1.Datasets4.2评价度量4.3.Impl......
  • 【Python】成功解决TypeError: ‘int’ object is not iterable
    【Python】成功解决TypeError:‘int’objectisnotiterable......