Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
68 views
in Technique[技术] by (71.8m points)

python - Calling a function from a class without object

I have a question. this is my code:

class student:
    def __init__(self, vnaam, anaam, nummer, geboorte, mail, cijfer):
        self.vnaam = vnaam
        self.anaam = anaam
        self.mail = mail
        self.nummer = nummer
        self.geboorte = geboorte
        self.cijfer = cijfer
        self.cijfers = []

    def mailadres(self):
        mailadres = self.nummer + "@rocfriesepoort.nl"
        mailadres = mailadres.replace(' ', "")
        mailadres = mailadres.lower()
        return mailadres

    def cijfervullen(self):
        self.cijfers.append(self.cijfer)

    def gemiddelde(self):
        gemid = (sum(self.cijfers) / len(self.cijfers))
        return gemid

student1 = student("Peter", "Veelsma", "123456", "23/4/2003", "", 8)
student2 = student("Anna", "Grijpstra", "325764", "11/9/2004", "", 7)
student3 = student("Bart", "van Tongeren", "876352", "9/11/2001", "", 5)

studenten = [student1, student2, student3]

for x in studenten:
    x.mail = (x.mailadres())
    x.cijfervullen()
    print(x.vnaam, x.anaam, "-", x.nummer, "-", x.mail, "-", x.geboorte, "-", "Cijfer:", *x.cijfers)

i want to use the funtion gemiddelde() wihout calling a object. i just want to print the output of that funtion. I already tried something with @staticmethod, but that doesnt work

how do i do this?

question from:https://stackoverflow.com/questions/65836991/calling-a-function-from-a-class-without-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

gemiddelde is an instance method. To call it, you need an instance:

print(student1.gemiddelde())

Instance methods are the most common type of methods in Python classes. These are so called because they can access unique data of their instance.

Here, gemiddelde needs access to the cijfers attribute.

Take a look at the documentation about Classes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...