繁体   English   中英

如何在 python 中定义名称?

[英]How do I define a name in python?

每当我运行我的代码时,我都会得到:NameError: name 'Object_Oriented_Programming' is not defined

如何定义名称 Object_Oriented_Programming?

代码:

class Object_Oriented_Programming:
    
    class Inheritance():
        def __init__(self, name, age):
            self.name = name
            self.age = age

        class SchoolMember():
            '''Represents any school member.'''

            def __init__(self, name, age):
                self.name = name
                self.age = age
                print('(Initialized SchoolMember: {})'.format(self.name))

            def tell(self):
                '''Tell my details.'''
                print('Name:"{}" Age:"{}"'.format(
                    self.name, self.age), end=" ")

        class Teacher(SchoolMember):
            '''Represents a teacher.'''

            def __init__(self, name, age, salary):
                Object_Oriented_Programming.Inheritance.SchoolMember.__init__(
                    self, name, age)
                self.salary = salary
                print('(Initialized Teacher: {})'.format(self.name))

            def tell(self):
                Object_Oriented_Programming.Inheritance.SchoolMember.tell(self)
                print('Salary: "{:d}"'.format(self.salary))

就我所关心的代码而言,我在终端上运行它并且没有任何问题,它简单地执行并且没有显示任何内容,因为没有打印任何内容。

现在,如果你真的想知道如何在 oops in Python 中定义一个 object,这里是实现它的方法:

  1. 首先,不要在 class 中创建一个 class,您应该只创建一个 class,然后编写__init__方法,包括姓名或年龄等所有内容。
  2. 执行此操作时,您可以在末尾创建一个新变量并将其 = class 名称(名称,年龄)。 例如,我附上了一个 img 来向您展示一段代码。

代码

代码:

        class train:
    def __init__(self, name, fare, seats, code):
        self.name = name
        self.fare = fare
        self.seats = seats
        self.code = code

    def train_Status(self):
        print(f"The name of the train is {self.name}")
        print(f"The seats is {self. seats}")

    def fare_Info(self):
        print(f"The fare is {self. fare}")

    def code_Info(self):
        print(f"The code is {self. code}")

    def tickets_Info(self):
        if(self.seats > 0):
            print(
                f"The seats are available for you...\nYour seat number is {self.seats}")
            self.seats = self.seats - 1
        elif(self.seats == 0):
            print("The seats are not available for you...")
        else:
            print("The server isnt updated yet. \nPlease try again later.")

    @staticmethod
    def greeting():
        print("Welcome to Rajdhani express!!")


Inter = train("Inter Express", 180, 12, 239340)
Inter.greeting()
Inter.fare_Info()
Inter.train_Status()
Inter.tickets_Info()
Inter.train_Status()
Inter.code_Info()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM